import * as cartActions from "./Store/Actions/CartAction"
import store from "./Store"
import { useEffect, useState } from "react"

const Cart = props => {
    let { cart } = store.getState()
    let [cartInfo, setCartInfo] = useState(cart)
    useEffect(() => {
        store.subscribe(function () {
            let { cart } = store.getState()
            setCartInfo(cart)
        })
        store.dispatch(cartActions.fetchCart) //action必须是一个对象,当前我们传递了一个函数,显然是不行的,我们需要一个中间件,帮我们处理传递函数的情况
    }, [])

    // console.log(cart)

    // 将数据从cart中解构出来
    let { data, err, isFetching } = cart;
    let loading = isFetching ? <h1>正在加载...</h1> : ""
    let errEl = err ? <h1>{err}</h1> : null
    return (
        <fieldset>
            <legend>购物车</legend>
            {loading}
            {errEl}
            <ul>
                {
                    data.map(item => {
                        return <li key={item.id}>{item.title}</li>
                    })
                }
            </ul>
        </fieldset>
    )
}

export default Cart